package com.ruoyi.common.utils.ocr;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class IDCardUtil {

    private static final DateTimeFormatter BIRTH_FMT =
        DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 根据身份证号返回当前周岁年龄
     * @param idCard 18 位身份证号
     * @return 年龄（周岁）；如果号码不合法返回 -1
     */
    public static int getAge(String idCard) {
        if (idCard == null || !idCard.matches("\\d{17}[\\dXx]")) {
            return -1;
        }
        try {
            LocalDate birthDate = LocalDate.parse(
                idCard.substring(6, 14),   // 第 7~14 位：yyyyMMdd
                BIRTH_FMT);
            return Period.between(birthDate, LocalDate.now()).getYears();
        } catch (Exception e) {
            return -1;
        }
    }
}
